package cn.ffcs.bpmpvc.services.impl;

import java.io.IOException;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Restrictions;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import cn.ffcs.bpmpvc.dao.ProductFlowDao;
import cn.ffcs.bpmpvc.services.AppBusinessReqService;
import cn.ffcs.bpmpvc.services.ProductFlowService;
import cn.ffcs.bpmpvc.services.bean.ConfigBean;
import cn.ffcs.bpmpvc.svc.ProcessPvcService;
import cn.ffcs.bpmpvc.svc.TaskAssignBean;
import cn.ffcs.bpmpvc.svc.TaskService;
import cn.ffcs.bpmpvc.utils.FileUtil;
import cn.ffcs.bpmpvc.utils.FlowContextUtil;
import cn.ffcs.bpmpvc.web.views.ProcessInstView;
import cn.ffcs.common.dao.AttachDAO;
import cn.ffcs.common.model.Attach;
import cn.ffcs.organ.model.Person;
import cn.ffcs.product.dao.ProductDAO;
import cn.ffcs.product.dao.ProductManagerDAO;
import cn.ffcs.product.dao.ProductReferenceDAO;
import cn.ffcs.product.model.Product;
import cn.ffcs.product.model.ProductManager;
import cn.ffcs.product.model.ProductReference;
import cn.ffcs.productdict.dao.ProductDictDAO;
import cn.ffcs.productdict.model.ProductDict;
import cn.ffcs.ref.dao.ProductRefSortDAO;
import cn.ffcs.ref.model.ProductRefSort;
import cn.ffcs.sort.service.IProductSortService;
import cn.ffcs.system.dict.model.Dict;
import cn.ffcs.system.dict.model.DictType;
import cn.ffcs.system.dict.service.DictService;
import cn.ffcs.system.dict.service.DictTypeService;

public class ProductFlowServiceImpl implements ProductFlowService {
	private ProductDAO<Product> productDAO;
	private ProductReferenceDAO<ProductReference> productReferenceDAO;
	private ProductManagerDAO<ProductManager> productManagerDAO;
	private ProductDictDAO<ProductDict> productDictDAO;
	private ProductRefSortDAO<ProductRefSort> productRefSortDAO;
	private AttachDAO<Attach> attachDAO;
	private ProductFlowDao productFlowDao;
	private ProcessPvcService processPvcService;
	private TaskService taskService;
	private ConfigBean configBean;
	private AppBusinessReqService appBusinessReqService;
	private DictTypeService<DictType> dictTypeService;
	private DictService<Dict> dictService;
	private IProductSortService productSortService;
	public void saveAndStartFlow(String processConfigId, Person startPerson,List<TaskAssignBean> nextTasksList, boolean isCommit,Product product,String productSortIdArr[],String propertyValueArr[],String infoIdsArr[],HttpServletRequest request) throws Exception {
		// 启动流程
		ProcessInstView processInstView = getProcessPvcService().startProcessInst(processConfigId, startPerson, nextTasksList, isCommit);
		product.setProcinstId(processInstView.getProcessStatus().getId().toString());
		product.setEnd(new Date());
		product.setReqCode(appBusinessReqService.getReqCode());
		productDAO.save(product);
		String productId=product.getId().toString();
		productDAO.deleteProductInfo(productId);
		productDAO.deletePerson(productId);
		
		saveProductOtherInfo(product, productSortIdArr, propertyValueArr, infoIdsArr, request);
	}

	private void saveProductOtherInfo(Product product, String[] productSortIdArr, String[] propertyValueArr, String[] infoIdsArr, HttpServletRequest request) throws IOException {
		//对产品附加动态属性设置
		if(propertyValueArr!=null&&propertyValueArr.length>0){
			for (int i = 0; i < propertyValueArr.length; i++) {
				productDAO.saveOneProductInfo(product, infoIdsArr[i], propertyValueArr[i]);
			}
		}
		
		//对产品对应的类型进行处理
		if(productSortIdArr!=null&&productSortIdArr.length>0){
			ProductRefSort productRefSort=null;
			for (int i = 0; i < productSortIdArr.length; i++) {
				if(StringUtils.isNotBlank(productSortIdArr[i])){
					productRefSort = new ProductRefSort();
		            productRefSort.setProduct(product.getId().toString());
		            productRefSort.setSort(productSortIdArr[i]);
		            productRefSort.setCreator(product.getCreator());
		            productRefSort.setBegin(new Date());
		            productRefSort.setEnd(FlowContextUtil.getEndDate());
		            productRefSortDAO.save(productRefSort);
				}
			}
		}
		ProductManager productManager =null;
		Person person =null;
		
		//新增产品主要负责人
		String mainPersons=request.getParameter("mainPersons");
		if(StringUtils.isNotBlank(mainPersons)){
			productManager = new ProductManager();
            person = new Person();
            person.setId(new Integer(mainPersons));
            productManager.setProduct(product);
            productManager.setPerson(person);
            productManager.setIsPrimary("1");
            // 设置有效时间
            productManager.setBegin(new Date());
            productManager.setEnd(FlowContextUtil.getEndDate());
            productManagerDAO.save(productManager);
		}
		//新增产品其他负责人
		String persons=request.getParameter("persons");
		if(StringUtils.isNotBlank(persons)){
			String personsArr[]=StringUtils.splitByWholeSeparator(persons, ",");
			for (int i = 0; i < personsArr.length; i++) {
				productManager = new ProductManager();
	            person = new Person();
	            person.setId(new Integer(personsArr[i]));
	            productManager.setProduct(product);
	            productManager.setPerson(person);
	            productManager.setIsPrimary("0");
	            // 设置有效时间
	            productManager.setBegin(new Date());
	            productManager.setEnd(FlowContextUtil.getEndDate());
	            productManagerDAO.save(productManager);
			}
		}
		
		//对附件进行处理
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		Iterator temp=multipartRequest.getFileNames();
		String fileShorName=null;
		ProductReference productReference=null;
		Date curDate=new Date();
		String imageFileNameTag="productImageFile";
		while(temp.hasNext()){
			String element = (String) temp.next();
			CommonsMultipartFile file = (CommonsMultipartFile) multipartRequest.getFile(element);
			if(StringUtils.isNotBlank(file.getOriginalFilename())){
				fileShorName = StringUtils.substringBeforeLast(file.getOriginalFilename(), ".");
				
				if(StringUtils.indexOf(element, imageFileNameTag)==-1){
					//对于文档上传的处理
					String eleNameArr[]=StringUtils.splitByWholeSeparator(element, "-");
					productReference=new ProductReference();
					productReference.setProduct(product);
					Dict dict=new Dict();
					dict.setId(Integer.valueOf(eleNameArr[1]));
					productReference.setBegin(curDate);
					productReference.setEnd(curDate);//暂不发布，归档后发布
					productReference.setReferenceType(dict);
					productReference.setTitle(fileShorName);
					productReference.setContent(fileShorName);
					productReference.setKeyword(fileShorName);
					productReference.setCreator(product.getCreator());
					productReferenceDAO.save(productReference);
					FileUtil.saveOneAttaFiles(multipartRequest, file, ProductReference.class.getName(),null, productReference.getId().toString());
				}else{
					//对于产品图片上传的处理
					FileUtil.saveOneAttaFiles(multipartRequest, file, Product.class.getName(),"pic", product.getId().toString());
				}
			}
		}
	}
	
	public void commitApplyTask(String flowTaskId,String content,String procinstId,List<TaskAssignBean> nextTasksList, boolean isCommit,Product productForm,String productSortIdArr[],String propertyValueArr[],String infoIdsArr[],HttpServletRequest request) throws Exception{
		Product product=getProductFlowDao().getByProinstId(procinstId);
		product.setName(productForm.getName());
		product.setDescription(productForm.getDescription());
		product.setIsClient(productForm.getIsClient());
		product.setIsNew(productForm.getIsNew());
		product.setBriefIntroduction(productForm.getBriefIntroduction());
		product.setLinkUrl(productForm.getLinkUrl());
		productDAO.save(product);
		//先删除原产品对应的相应信息
		String productId=product.getId().toString();
		productDAO.deleteProductInfo(productId);
		productDAO.deletePerson(productId);
		productDAO.deleteProductRefSort(product.getId());
		// 删除选择的附件
		String attactIdArr[] = request.getParameterValues("attactId");
		if (attactIdArr != null && attactIdArr.length > 0) {
			Attach attach=null;
			for (int i = 0; i < attactIdArr.length; i++) {
				attach=attachDAO.findById(Integer.valueOf(attactIdArr[i]));
				attachDAO.removeById(Integer.valueOf(attactIdArr[i]));
				if(attach.getRefEntity().equalsIgnoreCase(ProductReference.class.getName())){
					productReferenceDAO.removeById(Integer.valueOf(attach.getRefEntityID()));
				}
			}
		}
		//保存新的信息
		saveProductOtherInfo(product, productSortIdArr, propertyValueArr, infoIdsArr, request);
		if (isCommit) {
			getTaskService().completeTask(flowTaskId, content, nextTasksList);
		} else {
			getTaskService().saveTaskAssignUser(flowTaskId, content, nextTasksList);
		}
		
	}
	
	public void commitArchiveTask(String flowTaskId,String content,String procinstId,List<TaskAssignBean> nextTasksList, boolean isCommit) throws Exception{
		if (isCommit) {
			getTaskService().completeTask(flowTaskId, content, nextTasksList);
			Product product=getProductFlowDao().getByProinstId(procinstId);
			String productId=product.getId().toString();
			getProductFlowDao().updateProductRefer(productId);
			getProductFlowDao().updateProduct(productId);
			//列新产品 及上传方档的end时间
		} else {
			getTaskService().saveTaskAssignUser(flowTaskId, content, nextTasksList);
		}
	}
	
	public List getRefeTypeList() {
		// 根据实体名称获取字典类型
		String dtKey = new ProductReference().getClass().getSimpleName();
		Criterion condDt = Restrictions.eq("keyValue", dtKey.toUpperCase());
		List<DictType> ldt = this.dictTypeService.findBy(condDt);
		List<Dict> lRefType = null;
		if (ldt != null && ldt.size() > 0) {
			DictType dictType = (DictType) ldt.get(0);
			Criterion cond = Restrictions.eq("dictType.id", dictType.getId());

			lRefType = dictService.findByAndOrder(cond, "sorting", "asc");
		}
		return lRefType;
	}
	
	public String getProcessId() {
		String name = getConfigBean().getProductFlowProcessTag();
		Dict flowDict = appBusinessReqService.getAppBusinessReqDao().getDict(name);
		if (flowDict != null) {
			return flowDict.getKeyValue();
		}
		return "114";
	}
	
	public ProductDAO<Product> getProductDAO() {
		return productDAO;
	}
	public void setProductDAO(ProductDAO<Product> productDAO) {
		this.productDAO = productDAO;
	}
	public ProductReferenceDAO<ProductReference> getProductReferenceDAO() {
		return productReferenceDAO;
	}
	public void setProductReferenceDAO(ProductReferenceDAO<ProductReference> productReferenceDAO) {
		this.productReferenceDAO = productReferenceDAO;
	}
	public ProductManagerDAO<ProductManager> getProductManagerDAO() {
		return productManagerDAO;
	}
	public void setProductManagerDAO(ProductManagerDAO<ProductManager> productManagerDAO) {
		this.productManagerDAO = productManagerDAO;
	}
	public ProductDictDAO<ProductDict> getProductDictDAO() {
		return productDictDAO;
	}
	public void setProductDictDAO(ProductDictDAO<ProductDict> productDictDAO) {
		this.productDictDAO = productDictDAO;
	}
	public ProductRefSortDAO<ProductRefSort> getProductRefSortDAO() {
		return productRefSortDAO;
	}
	public void setProductRefSortDAO(ProductRefSortDAO<ProductRefSort> productRefSortDAO) {
		this.productRefSortDAO = productRefSortDAO;
	}

	public AttachDAO<Attach> getAttachDAO() {
		return attachDAO;
	}

	public void setAttachDAO(AttachDAO<Attach> attachDAO) {
		this.attachDAO = attachDAO;
	}

	public ProductFlowDao getProductFlowDao() {
		return productFlowDao;
	}

	public void setProductFlowDao(ProductFlowDao productFlowDao) {
		this.productFlowDao = productFlowDao;
	}

	public ProcessPvcService getProcessPvcService() {
		return processPvcService;
	}

	public void setProcessPvcService(ProcessPvcService processPvcService) {
		this.processPvcService = processPvcService;
	}

	public TaskService getTaskService() {
		return taskService;
	}

	public void setTaskService(TaskService taskService) {
		this.taskService = taskService;
	}

	public ConfigBean getConfigBean() {
		return configBean;
	}

	public void setConfigBean(ConfigBean configBean) {
		this.configBean = configBean;
	}

	public AppBusinessReqService getAppBusinessReqService() {
		return appBusinessReqService;
	}

	public void setAppBusinessReqService(AppBusinessReqService appBusinessReqService) {
		this.appBusinessReqService = appBusinessReqService;
	}

	public DictTypeService<DictType> getDictTypeService() {
		return dictTypeService;
	}

	public void setDictTypeService(DictTypeService<DictType> dictTypeService) {
		this.dictTypeService = dictTypeService;
	}

	public DictService<Dict> getDictService() {
		return dictService;
	}

	public void setDictService(DictService<Dict> dictService) {
		this.dictService = dictService;
	}

	public IProductSortService getProductSortService() {
		return productSortService;
	}

	public void setProductSortService(IProductSortService productSortService) {
		this.productSortService = productSortService;
	}


	
}
